#include "serialconfigdialog.h"
#include <QFormLayout>
#include <QRegExpValidator>

SerialConfigDialog::SerialConfigDialog(QString serialNum, int baudRate, QString parity, int dataBit, QString stopBit, QWidget *parent)
    :QDialog(parent), serialNum(serialNum), baudRate(baudRate), parity(parity),
      dataBit(dataBit), stopBit(stopBit)
{
    setWindowTitle("Serial Port Configuration");
    resize(300, 140);
    initUI();
}

void SerialConfigDialog::initUI()
{
    QFormLayout *layout = new QFormLayout;

    QLabel *serialNumLabel = new QLabel(tr("Serial Num"));
    QStringList serialNumList;
    for (int i = 1; i <= 20; ++i) {
        serialNumList.append("COM" + QString::number(i));
    }
    serialNumBox = new QComboBox;
    serialNumBox->addItems(exchangePlaceWithFirst(serialNumList, serialNum));

    QLabel *baudRateLabel = new QLabel(tr("Baud Rate"));
    QStringList baudRateList;
    baudRateList << "1200" << "2400" << "4800" << "9600"
                 << "19200" << "38400" << "57600" << "115200";
    baudRateBox = new QComboBox;
    baudRateBox->addItems(exchangePlaceWithFirst(baudRateList, QString::number(baudRate)));

    QLabel *parityLabel = new QLabel(tr("Parity"));
    QStringList parityList;
    parityList << "NONE" << "EVEN" << "ODD" << "MARK";
    parityBox = new QComboBox;
    parityBox->addItems(exchangePlaceWithFirst(parityList, parity));

    QLabel *dataBitLabel = new QLabel(tr("Data Bit"));
    QStringList dataBitList;
    dataBitList << "5" << "6" << "7" << "8";
    dataBitBox = new QComboBox;
    dataBitBox->addItems(exchangePlaceWithFirst(dataBitList, QString::number(dataBit)));

    QLabel *stopBitLabel = new QLabel(tr("Stop Bit"));
    dataBitList.clear();
    dataBitList << "1" << "1.5" << "2" ;
    stopBitBox = new QComboBox;
    stopBitBox->addItems(exchangePlaceWithFirst(dataBitList, stopBit));

    okBtn = new QPushButton(tr("OK"));
    cancelBtn = new QPushButton(tr("Cancel"));

    layout->addRow(serialNumLabel, serialNumBox);
    layout->addRow(baudRateLabel, baudRateBox);
    layout->addRow(parityLabel, parityBox);
    layout->addRow(dataBitLabel, dataBitBox);
    layout->addRow(stopBitLabel, stopBitBox);
    layout->addRow(okBtn, cancelBtn);

    connect(okBtn, &QAbstractButton::clicked, this, &QDialog::accept);
    connect(cancelBtn, &QAbstractButton::clicked, this, &QDialog::reject);
    setLayout(layout);
}

SerialConfigDialog::~SerialConfigDialog()
{
    delete serialNumBox, baudRateBox, dataBitBox, parityBox, stopBitBox;
    delete okBtn, cancelBtn;
}

QStringList exchangePlaceWithFirst(QStringList list, QString target)
{
    if(list.contains(target)){
        int targetIndex = list.indexOf(target);
        QString temp = list[0];
        list[0] = target;
        list[targetIndex] = temp;
        return list;
    } else {
        return list;
    }
}
